package main

import (
	"io/ioutil"
	"os"
	"os/exec"
	path "path/filepath"
	"regexp"
	"strings"
	"sync"
	"time"

	"github.com/howeyc/fsnotify"
	"github.com/silenceper/log"
)

var (
	cmd          *exec.Cmd
	state        sync.Mutex
	eventTime    = make(map[string]int64)
	scheduleTime time.Time
)

//NewWatcher new watcher
func NewWatcher(paths []string) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Errorf(" Fail to create new Watcher[ %s ]\n", err)
		os.Exit(2)
	}

	go func() {
		for {
			select {
			case e := <-watcher.Event:
				isbuild := true

				if !checkIfWatchExt(e.Name) {
					//log.Info("checkIfWatchExt" + e.Name)
					continue
				}

				mt := getFileModTime(e.Name)
				if t := eventTime[e.Name]; mt == t {
					//log.Infof("[SKIP] # %s #\n", e.String())
					isbuild = false
				}

				eventTime[e.Name] = mt

				if isbuild {
					go func(name string) {
						// Wait 1s before autobuild util there is no file change.
						scheduleTime = time.Now().Add(1 * time.Second)
						for {
							time.Sleep(scheduleTime.Sub(time.Now()))
							if time.Now().After(scheduleTime) {
								break
							}
							return
						}

						Autobuild(name)
					}(e.Name)
				}
			case err := <-watcher.Error:
				log.Errorf("%v", err)
				log.Warnf(" %s\n", err.Error()) // No need to exit here
			}
		}
	}()

	//log.Infof("Initializing watcher...\n")
	for _, path := range paths {
		//log.Infof("Directory( %s )\n", path)
		err = watcher.Watch(path)
		if err != nil {
			log.Errorf("Fail to watch directory[ %s ]\n", err)
			os.Exit(2)
		}
	}

}

// getFileModTime retuens unix timestamp of `os.File.ModTime` by given path.
func getFileModTime(path string) int64 {
	path = strings.Replace(path, "\\", "/", -1)
	f, err := os.Open(path)
	if err != nil {
		log.Errorf("Fail to open file[ %s ]\n", err)
		return time.Now().Unix()
	}
	defer f.Close()

	fi, err := f.Stat()
	if err != nil {
		log.Errorf("Fail to get file information[ %s ]\n", err)
		return time.Now().Unix()
	}

	return fi.ModTime().Unix()
}

//获取文件修改时间 返回unix时间戳
func GetFileModTime(path string) int64 {
	f, err := os.Open(path)
	if err != nil {
		log.Errorf("open file error:%s", path)
		return 0
	}
	defer f.Close()

	fi, err := f.Stat()
	if err != nil {
		log.Errorf("open file error:%s", path)
		return 0
	}

	// "2006-01-02 15:04:05.000000"
	// log.Infof("%s:%s", path, fi.ModTime().Format("2006-01-02 15:04:05.000000"))
	return fi.ModTime().UnixNano()
}

//Autobuild auto build
func Autobuild(file string) {
	state.Lock()
	defer state.Unlock()

	//log.Infof("Start building...\n")

	cmdName := cfg.AppName
	var err error
	args := []string{}
	args = append(args, cfg.RunArgs...)
	args = append(args, file)
	args = append(args, cfg.AfterArgs...)
	bcmd := exec.Command(cmdName, args...)
	//bcmd.Stdout = os.Stdout // 不出错不打印;
	bcmd.Stderr = os.Stderr
	// log.Infof("Run Args: %s %s", cmdName, strings.Join(args, " "))
	err = bcmd.Run()
	if err != nil {
		log.Infof("error:%+v\n", err)
	}
}

// Should ignore filenames generated by
// Emacs, Vim or SublimeText
func shouldIgnoreFile(filename string) bool {
	for _, regex := range ignoredFilesRegExps {
		r, err := regexp.Compile(regex)
		if err != nil {
			panic("Could not compile the regex: " + regex)
		}
		if r.MatchString(filename) {
			return true
		}
		continue
	}
	return false
}

// 需要关注的后缀名;
func checkIfWatchExt(name string) bool {
	for _, s := range cfg.WatchExts {
		if strings.HasSuffix(name, s) {
			return true
		}
	}
	return false
}

func readAppDirectories(directory string, paths *[]string) {
	fileInfos, err := ioutil.ReadDir(directory)
	if err != nil {
		return
	}

	useDirectory := false
	for _, fileInfo := range fileInfos {
		if isExcluded(path.Join(directory, fileInfo.Name())) {
			continue
		}

		if fileInfo.IsDir() == true && fileInfo.Name()[0] != '.' {
			readAppDirectories(directory+"/"+fileInfo.Name(), paths)
			continue
		}
		if useDirectory == true {
			continue
		}
		*paths = append(*paths, directory)
		useDirectory = true
	}
	return
}

// If a file is excluded
func isExcluded(filePath string) bool {
	for _, p := range cfg.ExcludedPaths {
		absP, err := path.Abs(p)
		if err != nil {
			log.Errorf("err =%v", err)
			log.Errorf("Can not get absolute path of [ %s ]\n", p)
			continue
		}
		absFilePath, err := path.Abs(filePath)
		if err != nil {
			log.Errorf("Can not get absolute path of [ %s ]\n", filePath)
			break
		}
		if strings.HasPrefix(absFilePath, absP) {
			log.Infof("Excluding from watching [ %s ]\n", filePath)
			return true
		}
	}
	return false
}
